package com.zhangkunhao.notes.service;

import com.zhangkunhao.notes.dao.BaseDao;
import com.zhangkunhao.notes.dao.Dao;
import com.zhangkunhao.notes.entity.DO.Jokes;
import com.zhangkunhao.notes.entity.DO.User;

import com.zhangkunhao.notes.util.UserUtil;

import java.util.ArrayList;

import java.util.List;
import java.util.Objects;


import static java.util.stream.Collectors.*;

/**
 * 与地狱笑话业务相关的逻辑处理
 *
 * @author 张坤浩
 */
public class JokeService {
    private User user;

    String temp = "SELECT `id`,`title`,`content`,`launcher_name` as  launcherName," +
            " `launch_time` as launchTime, `viewers`,`consuming_virtue` as consumingVirtue from `virtue`.`joke`";
    String sql1 = temp + " where `id`>?";
    String sql2 = "UPDATE `virtue`.`joke` SET `viewers` = ? where `launcher_name`=?";
    String sql3 = "INSERT INTO `virtue`.`joke`" +
            "(`title`, `content`, `launcher_name`,`consuming_virtue`)VALUES(?,?,?,?)";
    String sql4 = temp + " `launcher_name`=?";

    public JokeService() {
    }

    public JokeService(User user) {
        this.user = user;
    }

    Dao baseDao = BaseDao.getInstance();

    public List<Jokes> queryList(Object... args) {
        //执行dao层
        return baseDao.queryList(sql1, Jokes.class, args);
    }

    public int updatePerfect(Object... args) {
        //执行dao层
        return baseDao.update(sql2, args);
    }

    public Jokes query(Object... args) {
        //执行dao层
        return baseDao.query(sql4, Jokes.class, args);
    }

    /**
     * 分享笑话
     *
     * @param title
     * @param content
     * @param consumingVirtue
     * @return
     */
    public String shareJokes(String title, String content, Integer consumingVirtue) {
        //执行dao层
        int insertRow = baseDao.update(sql3, title, content, user.getUserName(), consumingVirtue);
        //从dao层接收数据并判断再返回controller层
        if (insertRow > 0) {
            return "地狱笑话发布成功";
        }
        return "地狱笑话发布失败";
    }


    /**
     * 阅读别人的笑话
     *
     * @param jokes
     * @param launchName
     * @param jokeTitle
     * @param userService
     * @return
     */
    public boolean readJoke(List<Jokes> jokes, String launchName, String jokeTitle, UserService userService) {
        //是否存在访问者想要阅读的笑话
        boolean searchJokesResult = false;
        if (jokes != null) {
            searchJokesResult = jokes.stream()
                    .anyMatch(jokes1 -> jokes1.getLauncherName().equals(launchName) && jokes1.getTitle().equals(jokeTitle));
        }
        //存在想要阅读的笑话，避免空指针异常
        if (searchJokesResult) {
            jokes.stream()
                    .filter(joke -> joke.getLauncherName().equals(launchName) && joke.getTitle().equals(jokeTitle))
                    .forEach(joke -> System.out.println("笑话发布者:" + joke.getLauncherName()
                            + " 标题：" + joke.getTitle() + " 内容：" + joke.getContent() + " 笑话发布时间:" + joke.getLaunchTime()));
            //获取看笑话消耗的功德量的集合
            List<Integer> jokeConsumingList = jokes.stream()
                    .filter(joke -> joke.getLauncherName().equals(launchName) && joke.getTitle().equals(jokeTitle))
                    .map(Jokes::getConsumingVirtue)
                    .collect(toList());
            //统计这次观看消耗的总的功德，不考虑一个用户发表两个标题一样的笑话，所以集合中只有一个元素
            //更新笑话访问者的功德量
            user.setPayVirtue(user.getPayVirtue() + jokeConsumingList.get(0));
            user.setInitVirtue(50 - user.getPayVirtue() + user.getGainVirtue());

            //调用工具类判断更新用户功德量是否成功
            int updateUserVirtueRow = UserUtil.editInformation(userService, user);
            System.out.println("你消费的总功德量：" + user.getPayVirtue() + "你当前的总功德量：" +
                    user.getInitVirtue() + "你获得的总功德量" + user.getGainVirtue());

            //得到当前笑话的先前用户访问记录,
            List<String> jokeViewerList = jokes.stream().filter(joke -> Objects.equals(joke.getLauncherName(), launchName) && joke.getTitle().equals(jokeTitle))
                    .map(Jokes::getViewers).collect(toList());

            //调用工具类返回最新的笑话访问记录
            String allRecord = UserUtil.judgeVisit(jokeViewerList, user);

            //更新笑话访问记录到数据库
            int perfectJokeViewerRow = this.updatePerfect(allRecord, launchName);
            //判断更新用户功德数据和笑话被访问记录是否成功
            return updateUserVirtueRow > 0 && perfectJokeViewerRow > 0;
        }
        return false;
    }

    public ArrayList<Jokes> jokesDetails(String userName, UserService userService) {
        boolean judgeExistence = UserUtil.judgeExistence(userService, userName);
        //用来存放所查看的用户看过的笑话的集合
        ArrayList<Jokes> readJokes = new ArrayList<>();
        if (judgeExistence) {
            //获取所有笑话
            List<Jokes> jokesList = this.queryList(0);
            for (Jokes joke : jokesList) {
                //调用工具类判断所查看的用户是否看过该笑话
                if (UserUtil.myContains(joke.getViewers(), userName)) {
                    readJokes.add(joke);
                }
            }
        } else {
            System.out.println("输入的用户名错误，当前用户不存在哦");
        }
        return readJokes;
    }
}
